package org.mklink.controller;

import cn.hutool.core.util.StrUtil;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.stage.DirectoryChooser;
import org.mklink.domain.ControlWrapper;
import org.mklink.domain.MkLink;
import org.mklink.enums.Constant;
import org.mklink.enums.ControlEnum;
import org.mklink.enums.LinkTypeEnum;
import org.mklink.util.*;

import java.io.File;
import java.util.Arrays;
import java.util.Locale;

/**
 * 操作入口
 */
public class MkLinkController {
    
    @FXML
    public Label fileSize;
    @FXML
    private TextField txtSource;
    
    @FXML
    private Button btnSource;
    
    @FXML
    private TextField txtTarget;
    
    @FXML
    private Button btnTarget;
    
    @FXML
    private Button btnLink;
    
    @FXML
    private Button btnUnLink;
    
    @FXML
    private Button btnOpenUrl;
    
    /**
     * 语言切换按钮
     */
    @FXML
    private Button btnLanguage;
    
    /**
     * 标签引用
     */
    @FXML
    private Label labSource;
    @FXML
    private Label labTarget;
    @FXML
    private Label labThread;
    @FXML
    private Label labWarning;
    @FXML
    private Label labInstructions;
    @FXML
    private Label labInstruction1;
    @FXML
    private Label labInstruction2;
    @FXML
    private Label labInstruction3;
    @FXML
    private Label labInstruction4;
    @FXML
    private Label labErrorLog;
    
    /**
     * 成功日志
     */
    @FXML
    private ListView<String> listViewSuccess;
    
    /**
     * 成功日志
     */
    @FXML
    private ListView<String> listViewError;
    
    /**
     * 线程数量
      */
    @FXML
    private TextField txtThreadCount;
    /**
     * 软链接实现类创建工厂
     */
    private MkLinkFactory mkLinkFactory = new MkLinkFactory();
    
    /**
     * 页面加载完成事件处理
     */
    @FXML
    private void initialize() {
        // 注册控件
        UI.registeredControls(new ControlWrapper<>(ControlEnum.TXT_TARGET,txtTarget)
                ,new ControlWrapper<>(ControlEnum.BTN_SOURCE,btnSource)
                ,new ControlWrapper<>(ControlEnum.BTN_TARGET,btnTarget)
                ,new ControlWrapper<>(ControlEnum.BTN_LINK,btnLink)
                ,new ControlWrapper<>(ControlEnum.BTN_UNLINK,btnUnLink)
                ,new ControlWrapper<>(ControlEnum.TXT_THREAD_COUNT,txtThreadCount)
                ,new ControlWrapper<>(ControlEnum.LABEL_FILE_SIZE,fileSize)
                ,new ControlWrapper<>(ControlEnum.LIST_VIEW_SUCCESS,listViewSuccess)
                ,new ControlWrapper<>(ControlEnum.LIST_VIEW_ERROR,listViewError)
        );
        int threadCount = AppUtil.calculateOptimalThreadCount();
        txtThreadCount.setText(threadCount+"");
        // 添加线程数输入框的数字验证
        txtThreadCount.textProperty().addListener((observable, oldValue, newValue) -> {
            if (!newValue.matches("\\d*")) {
                // 如果输入的不是数字，恢复到旧值
                txtThreadCount.setText(oldValue);
            } else if (!newValue.isEmpty() && !newValue.equals("0")) {
                // 如果输入的是有效数字且不为0，更新值
                try {
                    int value = Integer.parseInt(newValue);
                    if (value < 1) {
                        txtThreadCount.setText("1");
                    }
                } catch (NumberFormatException e) {
                    txtThreadCount.setText("1");
                }
            } else if (newValue.equals("0")) {
                // 如果输入0，自动改为1
                txtThreadCount.setText("1");
            } else if (newValue.isEmpty()) {
                // 如果为空，设置默认值1
                txtThreadCount.setText("1");
            }
        });
        // 初始化线程池
        new GlobalThreadPool(threadCount);
        
        // 初始化语言相关文本
        updateUIText();
    }
    
    /**
     * 更新界面文本
     */
    private void updateUIText() {
        // 更新按钮文本
        btnSource.setText(LanguageUtil.getString("button.source.choose"));
        btnTarget.setText(LanguageUtil.getString("button.target.choose"));
        btnLink.setText(LanguageUtil.getString("button.link"));
        btnUnLink.setText(LanguageUtil.getString("button.unlink"));
        btnOpenUrl.setText(LanguageUtil.getString("button.openurl"));
        
        // 更新标签文本
        labSource.setText(LanguageUtil.getString("label.source"));
        labTarget.setText(LanguageUtil.getString("label.target"));
        labThread.setText(LanguageUtil.getString("label.thread"));
        labWarning.setText(LanguageUtil.getString("label.warning"));
        labInstructions.setText(LanguageUtil.getString("label.instructions"));
        labInstruction1.setText(LanguageUtil.getString("instruction.1"));
        labInstruction2.setText(LanguageUtil.getString("instruction.2"));
        // 处理换行符
        String instruction3Text = LanguageUtil.getString("instruction.3");
        labInstruction3.setText(instruction3Text.replace("\\n", System.lineSeparator()));
        labInstruction4.setText(LanguageUtil.getString("instruction.4"));
        fileSize.setText(LanguageUtil.getString("label.log"));
        labErrorLog.setText(LanguageUtil.getString("label.errorlog"));
        
        // 更新提示文本
        txtSource.setPromptText(LanguageUtil.getString("textfield.source.prompt"));
        txtTarget.setPromptText(LanguageUtil.getString("textfield.target.prompt"));
        
        // 更新语言切换按钮文本
        btnLanguage.setText(LanguageUtil.getString("button.language.switch"));
    }
    
    /**
     * 切换语言
     */
    @FXML
    protected void onBtnLanguageSwitch() {
        if (LanguageUtil.getCurrentLocale().getLanguage().equals(Locale.SIMPLIFIED_CHINESE.getLanguage())) {
            LanguageUtil.switchToEnglish();
        } else {
            LanguageUtil.switchToChinese();
        }
        updateUIText();
    }
    
    /**
     * 源路径选择事件
     */
    @FXML
    protected void onBtnSourceChooser() {
        DirectoryChooser chooser=new DirectoryChooser();
        chooser.setTitle(LanguageUtil.getString("button.source.choose"));
        if(StrUtil.isNotEmpty(txtSource.getText())){
            chooser.setInitialDirectory(new File(txtSource.getText()));
        }
        File sourceFile = chooser.showDialog(btnSource.getScene().getWindow());
        if(sourceFile!=null){
            txtSource.setText(sourceFile.getAbsolutePath());
            txtTarget.setText(sourceFile.getAbsolutePath());
        }
    }
    
    /**
     * 映射路径选择事件
     */
    @FXML
    protected void onBtnTargetChooser() {
        DirectoryChooser chooser=new DirectoryChooser();
        chooser.setTitle(LanguageUtil.getString("button.target.choose"));
        if(StrUtil.isNotEmpty(txtTarget.getText()) && FileUtil.exist(txtTarget.getText())){
            chooser.setInitialDirectory(new File(txtTarget.getText()));
        }
        File sourceFile = chooser.showDialog(btnTarget.getScene().getWindow());
        if(sourceFile!=null){
            txtTarget.setText(sourceFile.getAbsolutePath());
        }
    }
    
    /**
     * 设置软连接
     */
    @FXML
    protected void onBtnLink() {
        UI.updateLabelText(ControlEnum.BTN_LINK, LanguageUtil.getString("button.link"));
        UI.setDisable(true, Arrays.asList(ControlEnum.LIST_VIEW_SUCCESS,ControlEnum.LIST_VIEW_ERROR));
        //根据mode值通过工厂获取具体调用哪个实现类
        mkLinkFactory.getFactory(LinkTypeEnum.J).mkLink(new MkLink(txtSource.getText(),txtTarget.getText(), LinkTypeEnum.J, Integer.parseInt(txtThreadCount.getText())));
    }
    
    /**
     * 取消软连接
     */
    @FXML
    protected void onBtnUnLink() {
        UI.updateLabelText(ControlEnum.BTN_UNLINK, LanguageUtil.getString("button.unlink"));
        UI.setDisable(true, Arrays.asList(ControlEnum.LIST_VIEW_SUCCESS,ControlEnum.LIST_VIEW_ERROR));
        //根据mode值通过工厂获取具体调用哪个实现类
        mkLinkFactory.getFactory(LinkTypeEnum.J).unMkLink(new MkLink(txtSource.getText()));
    }
    
    /**
     * 打开项目地址
     */
    @FXML
    protected void onBtnOpenUrl() {
        AppUtil.openBrowser(Constant.PROJECT_GIT.getCode());
    }
    
}
